﻿using System;
using System.Collections.Generic;
using System.Text;
using LoginServer.Converter;
using Common;

namespace LoginServer
{
    public partial class ManagerUserConnection
    {
        void Process_L_Update_Card(object[] param)
        {
            User user = convert_data.GetUserConnection(param);
            PlayerInfo player_info;
            // Number of cards in Deck
            int number = (int)(byte)param[1];

            // Retrieve Deck Data
            List<int> data = new List<int>();
            for (int i = 2; i < 2+number; i++)
            {
                data.Add((int)(byte)param[i]);
            }

            if (!Check_Store(user, data,out player_info))
            {
                Console.WriteLine("Update Card Error {0}: Store Error", user.User_ID);
                this.SendMessageToUserID(user.User_ID, MSG_GSM.L_Update_Error, 1);
                //Send L_Update_Error
            }

            if (!Check_Forbidden(user, data))
            {
                Console.WriteLine("Update Card Error {0}: Forbidden Error", user.User_ID);
                this.SendMessageToUserID(user.User_ID, MSG_GSM.L_Update_Error, 2);
                //Send L_Update_Error
            }

            player_info.Deck = data;
            Update_Db(user,player_info);
            //Send L_Update_OK
            this.SendMessageToUserID(user.User_ID, MSG_GSM.L_Update_OK);
        }
     
        //---------------------------------------Method---------------------------------

        bool Check_Store(User user,List<int> current_deck,out PlayerInfo p_info)
        {
            bool value=true;
            GetDB db = new GetDB();
            PlayerInfo player= db.GetDeckStore(user.User_ID);
            p_info = null;
            foreach (var item in current_deck)
            {
                if(!player.Storage.Remove(item)) 
                    return false;
            }
            p_info = player;
            return value;
        }

        bool Check_Forbidden(User user,List<int> current_deck)
        {
            bool value = true;
            GetDB db = new GetDB();
            foreach (var item in db.GetAllForbidden())
            {
                if (current_deck.FindAll(P => P == item.ID).Count > item.MaxNumber)
                    return false;
            }
            return value;
        }

        void Update_Db(User user,PlayerInfo player_info)
        {
            int[] S = new int[1000];
            GetDB db = new GetDB();

            foreach (var item in player_info.Deck)
            {
                S[item]++;
            }

            for (int i = 0; i < S.Length; i++)
            {
                if (S[i] == 0) continue;
                db.UpdateCard(user.User_ID, i, S[i]);
            }
        }
    }
}
